import React, {
    Component,
} from 'react';

import {
    StyleSheet,
    Text,
    View,
    Platform,
    FlatList,
    Dimensions,
    TouchableOpacity,
    Image,
    ScrollView,
    StatusBar,
    Linking,
    ActivityIndicator,
    DeviceEventEmitter,
    TextInput,
} from 'react-native';
// import AsyncStorage from '../../utils/AsyncStorage'//本地存储
import AsyncStorage from '@react-native-async-storage/async-storage';



import AndroidModule from 'src/utils/AndroidConnent'
import HttpUtils from "../../utils/HttpUtils";
import HttpUrls from "../../utils/HttpUrls";
import Constant from '../../utils/Constant'//全局变量
import Header from "../../components/header";
import Loading from "../../utils/Loading";

import NoData from "../../utils/NoData";

const isIos = Platform.OS == 'ios';
const screenW = Dimensions.get('window').width;
const screenH = Dimensions.get('window').height;
let chooseType=0;
let chooseAuthorizeId='';//所属企业
let tempchooseName=''
let navigation

export default class ChooseTemplatePage extends Component {

    constructor(props) {
        super(props);
        this.state = {
            contractCount:0,//剩余条数
            chooseName:'',//所选择的企业名称
            chooseCompanyId:'',
            templateList: [],      
            isRefresh: false,
            showFoot: 0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
            pageNo: 1
        }
    }

    componentWillUnmount() {
        if (this.commonEventLinster) {
            this.commonEventLinster.remove()
        }
    }

    componentWillMount(){
        //监听从已授权列表进行的选择后的回调
        this.commonEventLinster = DeviceEventEmitter.addListener('commonEvent', e => {
            if(e.type == 'chooseAuthorize'){
                chooseAuthorizeId=e.orgId
                this.setState({
                    chooseName:e.orgName
                }, function () {
                    this.handlerInfos(chooseAuthorizeId,this.state.chooseName)
                })    
            }
           
        });
    }


    componentDidMount() {
        chooseType=this.props.route.params.chooseType
        // chooseAuthorizeId=this.props.chooseAuthorizeId
        // tempchooseName=this.props.chooseNamez
        this.handlerInfos('','')
    }

    async handlerInfos(chooseAuthorizeId,tempchooseName){
        if(tempchooseName){
            await AsyncStorage.setItem('chooseName', tempchooseName);
        }else{
            //从缓存中获取上一次选择的授权公司名称
            const value=await AsyncStorage.getItem('chooseName')
            if(value){
                tempchooseName=value
            }
        }
        if(chooseAuthorizeId){
            await AsyncStorage.setItem('chooseAuthorizeId', chooseAuthorizeId);
        }else{
             //从缓存中获取上一次选择的授权公司id
            const value=await AsyncStorage.getItem('chooseAuthorizeId')
            console.log('value = ',value)
            if(value){
                chooseAuthorizeId=value
            }

        }

        if(tempchooseName == null || tempchooseName == 'null'  || tempchooseName == 'undefined'){
            tempchooseName=''
        }
        if(chooseAuthorizeId == null || chooseAuthorizeId == 'null'  || chooseAuthorizeId == 'undefined'){
            chooseAuthorizeId=''
        }

        this.setState({
            chooseName:tempchooseName,
            chooseCompanyId:chooseAuthorizeId
        })
        this.refreshData()
    }

    render() {
        navigation = this.props.navigation
        return (
            <View style={styles.container}>
                <Header navigation={navigation} Title={'选择合同模板'} />

                {/* 合同剩余条数 */}
                <View style={styles.contractCountContainer}>
                    <Text style={styles.contractCount}>合同剩余: {this.state.contractCount}份</Text>
                    <TouchableOpacity   
                        activeOpacity={0.8}
                        style={styles.chargeContainer}
                        onPress={this.gotocharge.bind(this)}>
                        <View>
                            <Text style={styles.chargeTitle}>充值</Text>
                        </View>
                    </TouchableOpacity>
                </View>

       
                <View style={styles.chooseTypeContainer}>
                    <Text style={styles.typeTitle}>模板所属企业:</Text>
                    <TouchableOpacity style={{flexDirection:'row',alignItems:'center'}} 
                            activeOpacity={0.8}
                            onPress={()=>{
                                this.chooseTemplate()
                            }}
                    >
                        <Text style={styles.typeValue}>{this.state.chooseName?this.state.chooseName:'请选择'}</Text>
                        <Image source={require('source/image/electron/choosetypearrow.png')}  style={styles.choosearrow} />
                    </TouchableOpacity>
                </View>
                
                {
                   this.renderList()
                }

             

            </View>
        )
    }

    //充值
    gotocharge(){
        navigation.navigate('ContractRechargePage')
    }

    //选择已授权企业
    chooseTemplate(){
        navigation.navigate('ChooseAlreadyAuthorizePage')
    }


    refreshData = () => {
        this.getCount()
        this.setState({
            isRefresh: true,
            pageNo: 1,
            templateList: []
        }, function () {
          
            this.templateLists()
        })
    }

        //获取数量
        getCount(){
            let param = {
                userId:Constant.userInfo.userId,
                merchantId:Constant.userInfo.merchantId,
            }
            HttpUtils.getRequest(HttpUrls.getByMerchantId, param)
                .then((result) => {
                    this.setState({
                        contractCount:result.data.contractAvalable
                    })
                    
                })
                .catch((error) => {
    
                });
        }

    templateLists() {

        let param = {
            pageNo: this.state.pageNo,
            pageSize: 20,
            merchantId: Constant.userInfo.merchantId,
            userId: Constant.userInfo.userId,
            belongTo:this.state.chooseCompanyId?this.state.chooseCompanyId:0,
            // belongTo:0,
            contractType:chooseType
        }
        HttpUtils.postRequest(HttpUrls.merchantSearchList, param)
            .then((result) => {
                // console.log('=============>>>>>>>>>>>>>>111111')
                // console.log(result)
                let data = result.data
                if (data) {
                    let resultList = data.resultList

                    if (resultList && resultList != null && resultList.length > 0) {

                        this.setState({
                            templateList: this.state.templateList.concat(resultList),
                            isRefresh: false,
                            showFoot: 1,
                        });
                        setTimeout(() => {
                            this.setState({
                                showFoot: resultList.length >= 20 ? 0 : 1,
                            })

                        }, 200);
                    } else {
                        this.setState({
                            showFoot: 1,
                            isRefresh: false,
                        });
                    }
                } else {
                    this.setState({
                        showFoot: 1,
                        isRefresh: false,
                    });
                }
            })
            .catch((error) => {

            });
    }

    renderHeader() {
        return (
            <View style={styles.header}>
            </View>
        );
    }

    renderList() {
        return (
            <View style={{ flex: 1 }}>
                <FlatList
                    data={this.state.templateList}
                    renderItem={this.renderItemView.bind(this)}
                    extraData={this.state}
                    ListHeaderComponent={this.renderHeader.bind(this)}
                    ListFooterComponent={this.renderFooter.bind(this)}
                    onEndReached={this._onEndReached.bind(this)}
                    onEndReachedThreshold={0.2}
                    onRefresh={this.refreshData}
                    refreshing={this.state.isRefresh}
                    ListEmptyComponent={this.renderEmpty.bind(this)}
                />

                <Loading onRef={(ref) => (this.Loading = ref)} />
            </View>
        )
    }

    renderItemView({ item, index }) {
        return (
            <TouchableOpacity key={index} style={styles.itemContain} activeOpacity={0.6}
            onPress={this.chooseTypeSelect.bind(this,item)}>
                <View  style={index == 0 ?styles.templateContainer:styles.templateContainerOther}>
                    <Image source={require('source/image/electron/templatepdf.png')}  style={styles.templateitemLeft} />
                    <Text style={styles.templateitemRight}>{item.templateName?item.templateName:'系统模板'}</Text>
                </View>

            </TouchableOpacity>
        )
    }

    //合同御览
    chooseTypeSelect(item){

        let params = {
            fileDownloadUrl: item.templateUrl,
            templateId:item.templateId+'',
            chooseType:chooseType
        }

        navigation.navigate('PrivewContractPage', params)
      
        
    }



    renderEmpty() {
        return (
            <NoData Desc="暂无数据" style={{ marginTop: gREM(200) }} />

        )
    }

    renderFooter() {
        if (this.state.showFoot === 1) {
            return null;

        } else if (this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator size="small" color="#999999" />
                    <Text style={styles.loadMoreTextStyle}>正在加载更多数据...</Text>
                </View>
            );
        } else if (this.state.showFoot === 0) {
            return null;
        }
    }

    _onEndReached() {
        console.log('_onEndReached')
        //如果是正在加载中或没有更多数据了，则返回
        if (this.state.showFoot != 0) {
            return null;
        }

        //底部显示正在加载更多数据
        this.setState(
            {
                showFoot: 2,
                pageNo: this.state.pageNo + 1
            }, function () {
                this.templateLists()
            });


    }

}

const styles = StyleSheet.create({

    container: {
        width: screenW,
        flex: 1,
        backgroundColor: '#f6f6f6'
    },

    contractCountContainer:{
        height:42,
        backgroundColor:'#ffffff',
        flexDirection: 'row',
        alignItems: 'center',
    },

    contractCount:{
        fontWeight: '400',
        fontSize: 14,
        color: '#333333',
        marginLeft:15
    },

    chargeContainer:{
        width: 52,
        height: 27,
        backgroundColor: '#FEFCEB',
        borderRadius:4,
        position:'absolute',
        right:15,
        alignItems:'center',
        justifyContent:'center',
    },

    chargeTitle:{
        fontWeight: '500',
        fontSize: 14,
        color: '#F96A0E'
    },

    chooseTypeContainer:{
        height:44,
        alignItems:'center',
        justifyContent:'center',
        flexDirection:'row',
        backgroundColor:'#ffffff'
    },

    typeTitle:{
        fontWeight: '400',
        fontSize: 14,
        color: '#333333',
    },

    typeValue:{
        fontWeight: '400',
        fontSize: 14,
        color: '#333333',
        marginLeft:5
    },

    choosearrow:{
        width:10,
        height:10,
        marginLeft:5,
    },



    itemContain: {
        backgroundColor: '#fff',
    },

    templateContainer:{
        marginLeft:16,
        marginRight:16,
        marginTop:16,
        marginBottom:16,
        width:screenW-32,
        height:94,
        backgroundColor:'#F4F4F4',
        borderRadius:8,
        flexDirection:'row',
        alignItems:'center'
    },

    templateContainerOther:{
        marginLeft:16,
        marginRight:16,
        marginBottom:16,
        width:screenW-32,
        height:94,
        backgroundColor:'#F4F4F4',
        borderRadius:8,
        flexDirection:'row',
        alignItems:'center'
    },

    templateitemLeft:{
        width:68,
        height:68,
        marginLeft:12,
    },

    templateitemRight:{
        fontSize: 16,
        color: '#333333',
        fontWeight: '500',
        marginLeft:17
    },

    chooseTypeContaner:{
        width:screenW,
        height:screenH,
        backgroundColor:'rgba(153, 153, 153, 0.5)',
        zIndex: 1000,
        position: "absolute",
        left: 0,
        bottom: 0,
        justifyContent: "center",
        alignItems: "center",
    },

    chooseTypeBottoms:{
        width:screenW,
        backgroundColor:'#f9f9f9',
        position:'absolute',
        bottom:0,
        height:230
    },

    chooseTypeTop:{
        alignItems:'center',
        flexDirection:'row',
        height:45,
        width:screenW,
        justifyContent:'center'
    },

    choosetypetitle:{
        fontWeight: '500',
        fontSize: 18,
        color: '#333333',
    },

    chooseclose:{
        right:15,
        position:'absolute'
    },

    chooseCenterContainer:{
        height:135,
        borderRadius:5,
        marginLeft:15,
        marginRight:15,
        backgroundColor:'#ffffff',
        flexDirection:'row',
        alignItems:'center'
    },

    funcontainer:{
        width:(screenW-30-32)/3,
        height:100,
        backgroundColor:'#F2F7FE',
        borderRadius:8,
        marginLeft:8,
        alignItems:'center',
        justifyContent:'center'
    },

    contractTypeIcon:{
        width:45,
        height:45
    },

    cobtractTypeTitle:{
        fontWeight: '500',
        fontSize: 12,
        color: '#000000',
        marginTop:8
    },

    header: {
        width: '100%',
        height: 10,
    },

    footer: {
        flexDirection: 'row',
        height: 40,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#f6f6f6'
    },
    loadMoreTextStyle: {
        fontSize: 14,
        color: '#999999',
        marginStart: 10,
    },



})